package woordvoorspeller.gui;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.StringTokenizer;


/**
 * WordListKeyListener is a KeyListener implementation. This class
 * updates the widget when a key is released. It calls updateSentence on
 * the widget.
 * @author Brian Setz
 * @version 0.1
 */
public class WordListKeyListener implements KeyListener
{
	private WordListWidget widget;
	
	/**
	 * Creates a WordListKeyListener.
	 * @param widget The widget that is going to use the KeyListener.
	 */
	public WordListKeyListener(WordListWidget widget)
	{
		this.widget = widget;
	}
	
	public void keyPressed(KeyEvent ke) { /* Do nothing */ }
	public void keyTyped(KeyEvent ke) { /* Do nothing */ }
	
	/**
	 * This event is triggered by a key release.
	 * @param ke The KeyEvent generated by the keyboard.
	 */
	public void keyReleased(KeyEvent ke) 
	{ 
		switch(ke.getKeyCode())
		{
			//Enter pressed:
			case 10:
				// Tokenize the string.
				StringTokenizer strTok = new StringTokenizer(widget.getSentence());
				
				// Parse each token.
				while(strTok.hasMoreTokens())
				{
					// Increase the priority of the given word.
					String word = strTok.nextToken();
					widget.getWordList().increasePriority(word);	
				}				
				// Empty the field.
				widget.updateSentence("");
				break;
			//F1 pressed:
			case 112:
				// Add the first word from the list to the sentence. 
				widget.updateSentence(widget.addWord(widget.getWord(0), widget.getSentence()));
				break;
			//F2 pressed:
			case 113:
				// Add the second word from the list to the sentence.				
				widget.updateSentence(widget.addWord(widget.getWord(1), widget.getSentence()));
				break;
			//F3 pressed:
			case 114:
				// Add the third word from the list to the sentence.
				widget.updateSentence(widget.addWord(widget.getWord(2), widget.getSentence()));
				break;
			default:
				// Update the widget.
				widget.updateSentence();
				break;
		}
	}
}
